package testing.hqlquery;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;

import org.hibernate.Session;
import org.hibernate.Transaction;

import core.util.HibernateCoreUtil;

public class TesHql {

	/**
	 * @param args
	 */
	public static void singleSelectQuery()
	{
		Long ProductId = 3L;
		String sql ="select c.path path from category c , category_product cp where c.uuid = cp.category_uuid and product_uuid = "+ProductId+" order by c.depth desc limit 0 ,1" ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				SQLQuery query = session.createSQLQuery(sql).addScalar("path", Hibernate.STRING);
				String p = (String) query.list().get(0);
				System.out.println(p);
				/*Iterator lst = query.list().iterator();
				while(lst.hasNext())
				{
					Long cateId = (Long) lst.next();
					System.out.println(cateId);
				}*/
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		singleSelectQuery() ;
	}
	public static void multiSelectQry()
	{
		Long ProductId = 1L;
		String sql ="select category_uuid, product_uuid from category_product where product_uuid="+ProductId;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				SQLQuery query = session.createSQLQuery(sql).addScalar("category_uuid", Hibernate.LONG).addScalar("product_uuid", Hibernate.LONG);
				Iterator lst = query.list().iterator();
				while(lst.hasNext())
				{
					Object[] obj = (Object[]) lst.next();
					System.out.println(obj[0]  + "---------" +  obj[1]);
				}
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
	}

}
